package org.halk.httpserver.entity;

import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 *
 * 对响应进行封装
 *
 * @Author zhuhao
 * @Date 2022/5/26 17:29
 * @desc
 */
@Data
@NoArgsConstructor
public class Response {

    private OutputStream outputStream;
    private Request request;

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    /**
     * 根据请求头中的资源文件名称，发送静态资源
     */
    public void sendStaticResource() throws IOException {

        //获取请求头中资源文件的名称
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("static/" + request.getUri().substring(1));

        if (inputStream != null) {
            // 需要先获取到资源文件的Path对象
            String contentType = Files.probeContentType(Paths.get(request.getUri()));
            // 添加HTTP响应头
            String responseHeader = "HTTP/1.1 200 OK\r\n" +
                    "Content-Type: " + contentType + "\r\n" +
                    "\r\n";
            outputStream.write(responseHeader.getBytes(StandardCharsets.UTF_8));

            // 发送文件内容
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } else {
            // 文件不存在时，输出404信息
            String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
                    "Content-Type: text/html\r\n" +
                    "\r\n" +
                    "404 File Not Found";
            try {
                this.outputStream.write(errorMessage.getBytes(StandardCharsets.UTF_8));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
